﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;

namespace Utilities
{
    /// <summary>
    /// 扩展已有类的一些方法简化调用
    /// </summary>
    public static class ExtensionsMethod
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
        public static int ToInt32(this String str)
        {
            return int.Parse(str);
        }
        public static string ToJSON(this object obj)
        {
            JavaScriptSerializer Seriallizer = new JavaScriptSerializer();
            string result = Seriallizer.Serialize(obj);
            //替换Json的Date字符串
            string p = @"\\/Date\(-{0,1}\d+\)\\/";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
            Regex reg = new Regex(p);
            result = reg.Replace(result, matchEvaluator);
            return result;
        }
        /// <summary>
        /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
        /// </summary>
        private static string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            DateTime dt = new DateTime(1970, 1, 1);
            Regex reg = new Regex(@"-{0,1}\d+");
            string x = reg.Match(m.Groups[0].Value).Value;
            dt = dt.AddMilliseconds(long.Parse(x));
            dt = dt.ToLocalTime();
            result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        }
        public static DateTime ToDate(this String str)
        {
            return DateTime.Parse(str);

        }
    }
}
